import clips
from pathlib import Path
import os
import sys
import json
import traceback

# set Active code page
if sys.platform.startswith("win"):
    os.system("chcp 65001 > nul")


def get_executable_dir() -> Path:
    if getattr(sys, 'frozen', False):
        return Path(sys.executable).parent.resolve()
    else:
        return Path(__file__).parent.resolve()


def get_resource_path(relative_path: str) -> Path:
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        return Path(sys._MEIPASS) / relative_path
    else:
        return get_executable_dir() / relative_path


def main():
    # input and output path
    input_path = get_resource_path("dsm5_expert_system.clp")
    output_path = get_executable_dir() / "dsm5_expert_system.json"

    # excute expert system
    env = clips.Environment()
    env.clear()
    env.load(str(input_path), binary=False)
    env.reset()
    env.run()

    # output
    result = {}
    for fact in env.facts():
        if fact.template.name == "chief-complaint":
            result['主诉症状'] = fact[0]
        if fact.template.name == "diagnosis":
            result['鉴别诊断'] = fact[0]

    print(f'DSM-5鉴别诊断专家系统：{result}')

    with open(output_path, 'w+', encoding='utf-8') as f:
        json.dump(result, f, indent=2, ensure_ascii=False)


if __name__ == "__main__":
    try:
        main()
        if sys.platform == "win32" and len(sys.argv) == 1:
            input("执行成功，按回车键退出...")
    except Exception as e:
        error_msg = f"错误: {str(e)}\n\n{traceback.format_exc()}"
        if sys.platform == "win32":
            import ctypes
            ctypes.windll.user32.MessageBoxW(0, error_msg, "程序崩溃", 0x10)
